//
//  UploadViewController.m
//  MIS Cloud
//
//  Created by goldeney on 14-7-23.
//  Copyright (c) 2014年 goldeneye. All rights reserved.
//

#import "UploadViewController.h"
#import "UploadFileHelper.h"
#import "FileUploadCell.h"
#import "FileTypeIcon.h"
#import "FileUploadModel.h"
#import "ASIFormDataRequest.h"
#import "PreviewLocalFileTypeViewController.h"
#import "FileAttributeModel.h"
#import "FileSizeFormatHelper.h"
#import "GEQLPreviewController.h"

@interface UploadViewController ()

@property (strong, nonatomic) UploadFileHelper *uploadFile;
@property(nonatomic,strong) NSString *numberType;
@property(nonatomic,strong) NSString *extension;
@property(nonatomic,strong) NSString *functionA;

@property(nonatomic,assign) BOOL isOtherUpLoad;

@end

@implementation UploadViewController
@synthesize uploadingTable = _uploadingTable;
@synthesize uploadFile = _uploadFile;
@synthesize extension = _extension;
@synthesize numberType = _numberType;
@synthesize functionA = _functionA;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"上传文件";
        
        //创建一个右边按钮
        UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"添加"
                                                                        style:UIBarButtonItemStyleDone target:self
                                                                       action:@selector(addButtonEvent:)];
        self.navigationItem.rightBarButtonItem = rightButton;
        
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"完成"
                                                                        style:UIBarButtonItemStyleDone target:self
                                                                       action:@selector(finishFileSelect:)];
        self.navigationItem.leftBarButtonItem = leftButton;
    }
    return self;
}

- (void)setNumberType:(NSString*)numberType extension:(NSString*)extension function:(NSString*)functionA
{
    self.numberType = numberType;
    self.extension = extension;
    self.functionA = functionA;
}

- (void)setNumberType:(NSString*)numberType extension:(NSString*)extension
{
    self.numberType = numberType;
    self.extension = extension;
    self.isOtherUpLoad = YES;
}

- (void)addButtonEvent:(id)sender
{
    //在一个文件的情况下，只能够添加一个
    if ([self.numberType intValue] == 1){
        if (self.uploadFile.uploadinglist.count>=1){
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"当前只能够添加一个文件,若要添加新文件，请删除当前列表文件后再试。" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
            return;
        }
    }
    
    MainAppDelegate *application = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
    PreviewLocalFileTypeViewController *viewController = [[PreviewLocalFileTypeViewController alloc] init];
    viewController.backResultDelagate = self;
    
    //设置文件上传个数
    if ([self.numberType intValue] == 1) //单个文件
    [viewController setSelectNumberType:FileSelectNumberTypeOne];
    else if([self.numberType intValue] == 2) //多个文件
    [viewController setSelectNumberType:FileSelectNumberTypeMultiple];
    
    //设置文件选择类型
    NSArray *fileType = [self.extension componentsSeparatedByString:@","];
    for (NSString *type in fileType) {
        [viewController addExtension:type];
    }
    
    [application.navigationController pushViewController:viewController animated:YES];
}

- (void)finishFileSelect:(id)sender
{
    NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
    for (FileUploadModel *model in _uploadFile.uploadinglist) {
        if (model.sendState != 1) {//存在未完成的项目
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您目前还存在未上传或上传失败的文件，是否放弃上传？" delegate:self cancelButtonTitle:@"放弃上传" otherButtonTitles:@"继续上传",nil];
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
            return;
        }
        if(!self.isOtherUpLoad) model.functionA = _functionA;
        [dataArray addObject:model];
    }
    
    if ([self.backResultDelagate respondsToSelector:@selector(backResultDataKey:dataValue:)]) {
        [self.backResultDelagate backResultDataKey:self.key dataValue:dataArray];
    }
    
    MainAppDelegate *application = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
    [application.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _uploadFile = [[UploadFileHelper alloc] init];
    _uploadFile.delegate = self;
    
    self.uploadingTable.tableFooterView = [[UIView alloc] init];
    [self.uploadingTable registerClass:[FileUploadCell class] forCellReuseIdentifier:@"FileUploadCell"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    _uploadingTable = nil;
    _uploadFile = nil;
}

#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {//放弃上传
        NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
        for (FileUploadModel *model in _uploadFile.uploadinglist) {
            [model.request clearDelegatesAndCancel];
            //获取上传成功文件
            if (model.sendState == 1) {
                if(!self.isOtherUpLoad) model.functionA = _functionA;
                [dataArray addObject:model];
            }
        }
        
        if ([self.backResultDelagate respondsToSelector:@selector(backResultDataKey:dataValue:)]) {
            [self.backResultDelagate backResultDataKey:self.key dataValue:dataArray];
        }
        
        MainAppDelegate *application = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
        [application.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark -表格数据源
#pragma mark UITableViewDataSource


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 38;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) return  nil;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    lable.text = sectionTitle;
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.2];
    [view addSubview:lineView];
    
    return view;
}

//每个section显示的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            NSMutableString *newString = [[NSMutableString alloc] init];
            [newString appendString:@"上传文件"];
            [newString appendString:@" ("];
            [newString appendString:[[NSString alloc] initWithFormat:@"%lu",(unsigned long)_uploadFile.uploadinglist.count]];
            [newString appendString:@")"];
            return newString;
        }
        default:
            return @"Unknown";
    }
}

//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;//返回标题数组中元素的个数来确定分区的个数
}


//指定每个分区中有多少行，默认为1
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return [self.uploadFile.uploadinglist count];
            break;
        default:
            return 0;
            break;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //正在下载的文件列表
    if(indexPath.section == 0){
        static NSString *downCellIdentifier=@"FileUploadCell";
        FileUploadCell *cell=(FileUploadCell *)[self.uploadingTable dequeueReusableCellWithIdentifier:downCellIdentifier];
        
        FileUploadModel *fileInfo = [self.uploadFile.uploadinglist objectAtIndex:indexPath.row];
        cell.fileName.text=fileInfo.fileName;
        cell.fileInfo = fileInfo;
        [cell.operateButton addTarget:self action:@selector(operateTask:) forControlEvents:UIControlEventTouchUpInside];
        
        //设置上传按钮图片
        cell.fileIcon.image = [FileTypeIcon setFileTypeIcon:fileInfo.fileName];
        
        //设置上传进度
        NSString *fileSize = [NSString stringWithFormat:@"%lld",fileInfo.fileSize];
        NSString *sendSize = [NSString stringWithFormat:@"%lld",fileInfo.sendSize];
        double progressValue = [sendSize doubleValue] / [fileSize doubleValue];
        if (progressValue>1.00) progressValue = 1.00;
        [cell.progress setProgress:progressValue];
        
        //设置上传大小及总大小
        NSMutableString *sizeStr = [[NSMutableString alloc] init];
        [sizeStr appendString:[FileSizeFormatHelper getFileSizeString:sendSize]];
        [sizeStr appendString:@"/"];
        [sizeStr appendString:[FileSizeFormatHelper getFileSizeString:fileSize]];
        cell.fileCurrentSize.text = sizeStr;
        
        //文件正在上传状态
        if(fileInfo.sendState == 0){//正在连接状态
            NSMutableString *sizeCurrent = [[NSMutableString alloc] initWithFormat:@"%.0f",progressValue*100];
            [sizeCurrent appendString:@"%"];
            cell.fileSize.text = sizeCurrent;
            cell.fileSize.textColor = [UIColor blackColor];
            [cell.progress setfForegroundImage:[UIImage imageNamed:@"progress_green.png"]];
            [cell.operateIcon setImage:[UIImage imageNamed:@"btn_icon_delect.png"]];
            [cell.operateText setText:@"删除"];
            
        } else if(fileInfo.sendState == 1) {//上传完成
            cell.fileSize.text = @"上传完成";
            [cell.progress setfForegroundImage:[UIImage imageNamed:@"progress_green.png"]];
            cell.fileSize.textColor = [UIColor blackColor];
            [cell.operateIcon setImage:[UIImage imageNamed:@"btn_icon_delect.png"]];
            [cell.operateText setText:@"删除"];
            
        } else if(fileInfo.sendState == 2) {//上传异常
            cell.fileSize.text = @"上传异常";
            cell.fileSize.textColor = [UIColor redColor];
            [cell.progress setfForegroundImage:[UIImage imageNamed:@"progress_yellow.png"]];
            [cell.operateIcon setImage:[UIImage imageNamed:@"btn_icon_upload.png"]];
            [cell.operateText setText:@"重新上传"];
            
        }else if(fileInfo.sendState == 3) {//上传失败
            cell.fileSize.text = @"上传失败";
            cell.fileSize.textColor = [UIColor redColor];
            [cell.progress setfForegroundImage:[UIImage imageNamed:@"progress_yellow.png"]];
            [cell.operateIcon setImage:[UIImage imageNamed:@"btn_icon_upload.png"]];
            [cell.operateText setText:@"重新上传"];
        }
        
        return cell;
    }
    
    return nil;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(void)updateCellOnMainThread:(FileUploadModel *)fileInfo
{
    //改变列表进度
    for(id obj in self.uploadingTable.visibleCells)
    {
        if([obj isKindOfClass:[FileUploadCell class]])
        {
            FileUploadCell *cell=(FileUploadCell *)obj;
            if(cell.fileInfo.filePath == fileInfo.filePath) {
                //设置下载进度
                NSString *fileSize = [NSString stringWithFormat:@"%lld",fileInfo.fileSize];
                NSString *sendSize = [NSString stringWithFormat:@"%lld",fileInfo.sendSize];
                double progressValue = [sendSize doubleValue] / [fileSize doubleValue];
                if (progressValue>1.00) progressValue = 1.00;
                [cell.progress setProgress:progressValue];
                
                NSMutableString *sizeCurrent = [[NSMutableString alloc] initWithFormat:@"%.0f",progressValue*100];
                [sizeCurrent appendString:@"%"];
                cell.fileSize.text = sizeCurrent;
                
                //设置下载大小及总大小
                NSMutableString *sizeStr = [[NSMutableString alloc] init];
                [sizeStr appendString:[FileSizeFormatHelper getFileSizeString:sendSize]];
                [sizeStr appendString:@"/"];
                [sizeStr appendString:[FileSizeFormatHelper getFileSizeString:fileSize]];
                cell.fileCurrentSize.text = sizeStr;
            }
        }
    }
}


#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        FileUploadModel *fileInfo=[self.uploadFile.uploadinglist objectAtIndex:indexPath.row];
        GEQLPreviewController *newViewController = [[GEQLPreviewController alloc] initWithPathString:fileInfo.filePath];
        [self presentViewController:newViewController animated:YES completion:nil];
    }
}


#pragma 下载更新界面的委托
#pragma mark FileUploadDelegate
-(void)updateCellProgress:(ASIHTTPRequest *)request sendBytes:(long long)bytes
{
    FileUploadModel *fileInfo= [request.userInfo objectForKey:@"userInfo"];
    [self performSelectorOnMainThread:@selector(updateCellOnMainThread:) withObject:fileInfo waitUntilDone:YES];
}

-(void)failedUpload:(ASIHTTPRequest *)request error:(NSError*)error;
{
    [self.uploadingTable reloadData];
}

-(void)finishedUpload:(ASIHTTPRequest *)request
{
    [self.uploadingTable reloadData];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    NSMutableArray *fileArray = backValue;
    for (id dataModel in fileArray) {
        if ([dataModel isKindOfClass:[FileAttributeModel class]]) {
            FileAttributeModel *model = dataModel;
            [_uploadFile addUploadFileUrl:model.absolutePath];
        }
    }
    
    [self.uploadingTable reloadData];
}

-(void)operateTask:(id)sender
{
    UIButton *btnOperate=(UIButton *)sender;
    FileUploadModel *fileInfo= [self.uploadFile.uploadinglist objectAtIndex:btnOperate.tag];
    
    if(fileInfo.sendState == 0) {//正在连接状态
        [fileInfo.request cancel];
        [_uploadFile.uploadinglist removeObjectAtIndex:btnOperate.tag];
        
    } else if(fileInfo.sendState == 1){//上传完成
        [fileInfo.request cancel];
        [_uploadFile.uploadinglist removeObjectAtIndex:btnOperate.tag];
        
    } else if(fileInfo.sendState == 2){//上传异常
        NSString *filePath = fileInfo.filePath;
        [fileInfo.request cancel];
        [_uploadFile.uploadinglist removeObjectAtIndex:btnOperate.tag];
        [_uploadFile addUploadFileUrl:filePath];
        
    } else if(fileInfo.sendState == 3){//上传失败
        NSString *filePath = fileInfo.filePath;
        [fileInfo.request cancel];
        [_uploadFile.uploadinglist removeObjectAtIndex:btnOperate.tag];
        [_uploadFile addUploadFileUrl:filePath];
        
    }
    
    //更新table的数据
     [self.uploadingTable reloadData];
}

@end
